import { ref } from 'vue'
import { adapter, request } from '@/request'
import { negativeWordsByPost } from '@/core/api/promotion'
import type { Mode } from '@/core/interfaces/common'
import type { RequestWrapper } from '@/core/interfaces/common'
import type { NegativeWord } from '@/core/interfaces/negative'
import is from '@/utils/is'
import { message } from 'ant-design-vue'

export interface NegativeWordParams {
  name: NegativeWord['name']
  keyword?: NegativeWord['keyword']
  orderId: NegativeWord['orderId']
  orderWordId?: NegativeWord['orderWordId']
  campaignId: NegativeWord['campaignId']
  groupId: NegativeWord['groupId']
  matchType: NegativeWord['matchType']
  scopeType: NegativeWord['scopeType']
}

export default function updateNegativeWords() {
  const service = adapter<RequestWrapper<any>>(request)
  const loading = ref(false)

  const fetch = (data: Partial<NegativeWordParams>, mode: Mode) => {
    const { url, method } = negativeWordsByPost(mode)
    loading.value = true

    return service({
      config: {
        url,
        method,
        data
      },
      error: (err) => {
        if (is.error(err)) {
          message.error(err.message)
        }
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [null, fetch, loading] as const
}
